package com.naszetatry.login;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.naszetatry.beans.User;
import com.naszetatry.controller.LoginController;
import com.naszetatry.controller.UserController;
import com.naszetatry.exception.InvalidLoginException;
import com.naszetatry.exception.InvalidPasswordException;
import com.naszetatry.exception.NotActivatedException;
import com.naszetatry.logic.UserLogic;

/**
 * Serwlet odpowiedzialny za logowanie i wylogowanie.
 * @author Maciej Koch
 *
 */
public class Login extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if("logout".equals(request.getParameter("do"))) {
			UserController.logout(request.getSession());
			getServletContext().getRequestDispatcher("/main").forward(request, response);
			return;
		}
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setLogin(login);
		user.setPassword(password);
		LValidation validation = new LValidation();
		
		try {
			user = UserLogic.login(user);
		} catch (InvalidLoginException e) {		
			validation.isLoginValid = false;
		} catch (InvalidPasswordException e) {
			validation.isPasswordValid = false;
		} catch (NotActivatedException e) {
			validation.isActivated = false;
		}
		boolean loginAccepted = validation.isActivated && validation.isLoginValid && validation.isPasswordValid;
		
		if(loginAccepted)
			UserController.setCurrentUser(request.getSession(), user);
		else {
			LoginController.setValidation(request, validation);
		}
		
		getServletContext().getRequestDispatcher("/main").forward(request, response);
	}
}
